package task01;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;

public class FactorizerTest {
    private Factorizer factorizer;
    private ExecutorService executorService;

    protected static final int CYCLES = 1_000_000;

    @Before
    public void setUp() {
        factorizer = new Factorizer();
        executorService = Executors.newFixedThreadPool(32);
    }

    @Test
    public void testInvokeCounter() {
        submitTasks();
    }

    public void submitTasks() {
        for (int i = 0; i < CYCLES; i++) {
            executorService.submit(newTask());
        }
    }

    protected Runnable newTask() {
        return new Runnable() {
            @Override public void run() { factorizer.factorize(100); }
        };
    }

    @After
    public void collectResults() throws InterruptedException {
        waitAllTasks();
        checkResults();
    }

    public void waitAllTasks() throws InterruptedException {
        executorService.shutdown();
        assertTrue(executorService.awaitTermination(5, TimeUnit.SECONDS));
    }

    public void checkResults() {
        assertEquals(CYCLES, factorizer.getInvokeCount());
    }
}
